<template>
  <div class="auth-container fade-in">
    <div class="auth-card content-stagger">
      <h2 class="auth-title scale-in">注册</h2>
      <form class="auth-form" @submit.prevent="handleRegister">
        <div class="form-group">
          <label for="username">用户名</label>
          <input
            id="username"
            type="text"
            v-model="registerForm.username"
            placeholder="请输入用户名"
            class="form-input"
            :class="{ 'is-invalid': errors.username }"
            @blur="validateField('username')"
          />
          <span v-if="errors.username" class="error-message">{{ errors.username }}</span>
        </div>

        <div class="form-group">
          <label for="email">邮箱</label>
          <input
            id="email"
            type="email"
            v-model="registerForm.email"
            placeholder="请输入邮箱"
            class="form-input"
            :class="{ 'is-invalid': errors.email }"
            @blur="validateField('email')"
          />
          <span v-if="errors.email" class="error-message">{{ errors.email }}</span>
        </div>

        <div class="form-group">
          <label for="password">密码</label>
          <input
            id="password"
            type="password"
            v-model="registerForm.password"
            placeholder="请输入密码"
            class="form-input"
            :class="{ 'is-invalid': errors.password }"
            @blur="validateField('password')"
          />
          <span v-if="errors.password" class="error-message">{{ errors.password }}</span>
        </div>

        <div class="form-group">
          <label for="confirmPassword">确认密码</label>
          <input
            id="confirmPassword"
            type="password"
            v-model="registerForm.confirmPassword"
            placeholder="请再次输入密码"
            class="form-input"
            :class="{ 'is-invalid': errors.confirmPassword }"
            @blur="validateField('confirmPassword')"
          />
          <span v-if="errors.confirmPassword" class="error-message">{{
            errors.confirmPassword
          }}</span>
        </div>

        <button type="submit" class="btn btn-primary">注册</button>

        <div class="form-footer">
          <button type="button" class="btn-link" @click="navigateToLogin()">
            已有账号？立即登录
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import request from '@/api/request'

const router = useRouter()
const registerForm = ref({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
})
const errors = ref({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
})

// 自定义消息队列
const messages = ref([])
let messageId = 0

// 添加消息
const showMessage = (message, type = 'success', duration = 3000) => {
  const id = messageId++
  messages.value.push({
    id,
    message,
    type,
    show: false,
  })

  // 确保DOM已更新
  nextTick(() => {
    const msg = messages.value.find((m) => m.id === id)
    if (msg) {
      msg.show = true

      setTimeout(() => {
        msg.show = false
        setTimeout(() => {
          messages.value = messages.value.filter((m) => m.id !== id)
        }, 300)
      }, duration)
    }
  })
}

// 验证规则
const validateRules = {
  username: [
    { required: true, message: '请输入用户名' },
    { min: 3, max: 20, message: '用户名长度在3-20个字符之间' },
  ],
  email: [
    { required: true, message: '请输入邮箱' },
    {
      pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
      message: '请输入正确的邮箱格式',
    },
  ],
  password: [
    { required: true, message: '请输入密码' },
    { min: 6, message: '密码长度不能少于6位' },
  ],
  confirmPassword: [
    { required: true, message: '请确认密码' },
    {
      validator: (value) => value === registerForm.value.password,
      message: '两次输入的密码不一致',
    },
  ],
}

// 验证单个字段
const validateField = (field) => {
  const value = registerForm.value[field]
  const rules = validateRules[field]
  let error = ''

  for (const rule of rules) {
    if (rule.required && !value) {
      error = rule.message
      break
    }
    if (rule.min && value.length < rule.min) {
      error = rule.message
      break
    }
    if (rule.max && value.length > rule.max) {
      error = rule.message
      break
    }
    if (rule.pattern && !rule.pattern.test(value)) {
      error = rule.message
      break
    }
    if (rule.validator && !rule.validator(value)) {
      error = rule.message
      break
    }
  }

  errors.value[field] = error
  return !error
}

// 验证整个表单
const validateForm = () => {
  let isValid = true
  Object.keys(validateRules).forEach((field) => {
    if (!validateField(field)) {
      isValid = false
    }
  })
  return isValid
}

const handleRegister = () => {
  if (validateForm()) {
    request
      .post('/user/register', registerForm.value)
      .then((response) => {
        showMessage('注册成功，请登录', 'success')
        router.push('/login')
      })
      .catch((error) => {
        showMessage('注册失败: ' + (error.response?.data?.message || '未知错误'), 'error')
      })
  }
}

const navigateToLogin = () => {
  router.push('/login')
}


</script>

<style scoped>
.auth-container {
  /* background: linear-gradient(135deg, #f8fff8 0%, #f0f9f0 100%); */
  display: flex;
  align-items: center;
  justify-content: center;
}

.auth-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(39, 174, 96, 0.15);
  padding: 40px;
  width: 100%;
  max-width: 400px;
  border: 1px solid rgba(39, 174, 96, 0.1);
  text-align: center;
}

.logo {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 30px;
  cursor: pointer;
}

.music-icon {
  width: 32px;
  height: 32px;
  color: var(--success-color);
  margin-right: 10px;
}

.logo span {
  font-size: 24px;
  font-weight: bold;
  color: #2c3e50;
}

.auth-title {
  text-align: center;
  color: #2c3e50;
  margin-bottom: 30px;
  font-size: 28px;
  font-weight: 600;
}

.auth-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  text-align: left;
}

.form-group label {
  font-weight: 600;
  margin-bottom: 8px;
  color: #2c3e50;
}

.form-input {
  padding: 12px 16px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 16px;
  transition: all 0.3s ease;
  background: white;
}

.form-input:focus {
  outline: none;
  border-color: var(--success-color);
  box-shadow: 0 0 0 3px rgba(39, 174, 96, 0.1);
}

.form-input.is-invalid {
  border-color: #ff4757;
}

.error-message {
  color: #ff4757;
  font-size: 14px;
  margin-top: 4px;
}

.btn {
  padding: 14px 28px;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-primary {
  background: linear-gradient(135deg, #27ae60, #2ecc71);
  color: white;
  box-shadow: 0 4px 15px rgba(39, 174, 96, 0.3);
}

.btn-primary:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(39, 174, 96, 0.4);
}

.form-footer {
  margin-top: 20px;
  text-align: center;
}

.btn-link {
  background: none;
  border: none;
  color: var(--success-color);
  cursor: pointer;
  font-size: 14px;
  text-decoration: underline;
}

.btn-link:hover {
  color: #218c54;
}

@media (max-width: 768px) {
  .auth-card {
    padding: 30px 20px;
    margin: 20px;
  }
}

/* 自定义消息提示样式 */
.custom-message {
  position: fixed;
  top: 20px;
  right: 20px;
  padding: 10px 20px;
  border-radius: 8px;
  color: white;
  font-size: 14px;
  z-index: 9999;
  opacity: 0;
  transform: translateX(20px);
  transition:
    opacity 0.3s,
    transform 0.3s;
}

.custom-message.show {
  opacity: 1;
  transform: translateX(0);
}

.custom-message-success {
  background-color: var(--success-color);
}

.custom-message-error {
  background-color: var(--error-color);
}
</style>
